/*
 * @(#)OXMapperImpl.java    May 17, 2010
 *
 * Copyright 2009 Nyber Shanghai, Inc. All rights reserved.
 */

package com.common.oxm;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.XmlMappingException;

public class OxMapperImpl implements OxMapper {

	private Marshaller marshaller;
	private Unmarshaller unmarshaller;

	@SuppressWarnings("unchecked")
	public <T> T readObjectFromXml(Class<T> clazz, String filename)
			throws IOException {
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(filename);
			StreamSource stream = new StreamSource(fis);

			return (T) unmarshaller.unmarshal(stream);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				fis.close();
			}
		}

		return null;
	}

	public void writeObjectToXml(Object object, String filename)
			throws IOException {
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(filename);
			StreamResult stream = new StreamResult(fos);
			marshaller.marshal(object, stream);
		} catch (XmlMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fos != null) {
				fos.close();
			}
		}
	}

	public Marshaller getMarshaller() {
		return marshaller;
	}

	public void setMarshaller(Marshaller marshaller) {
		this.marshaller = marshaller;
	}

	public Unmarshaller getUnmarshaller() {
		return unmarshaller;
	}

	public void setUnmarshaller(Unmarshaller unmarshaller) {
		this.unmarshaller = unmarshaller;
	}

}
